<!--
 * @Description: 租户管理
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2022-07-11 13:43:40
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-08-10 11:20:37
-->
<template>
  <div class="tenant-container">
    <fks-query-page
      v-loading="loading"
      :data="tableDataForShow"
      :total="total"
      :page-size.sync="pageSize"
      :current-page.sync="currentPage"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 50, 100]"
      :element-loading-text="LANG.LOADING"
      :table-name="LANG.TENANT_LIST"
      @sort-change="tenantSortHandler"
      @query="getData"
      ref="tenantTable"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-button
            v-permission="['tenant:add']"
            type="primary"
            icon="fks-icon-plus"
            @click="addHandle"
            v-saas="['main', 'notSaas']"
          >
            <span> {{ LANG.ADD }}</span>
          </fks-button>
        </div>
      </template>
      <template>
        <fks-table-column type="index" align="center" label="#">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </fks-table-column>
        <fks-table-column
          prop="tenantId"
          align="left"
          label="ID"
          width="150px"
        />
        <fks-table-column
          prop="tenantName"
          :label="LANG.TENANT_NAME"
          align="left"
          sortable="custom"
        />
        <fks-table-column :label="LANG.MASTER_DATA" align="left" width="280px">
          <template slot-scope="scope">
            <fks-tag
              v-for="(tagLabel, index) in getMasterData(scope.row)"
              :key="index"
              style="margin: 4px"
              >{{ tagLabel }}
            </fks-tag>
          </template>
        </fks-table-column>
        <!-- <fks-table-column
          :label="LANG.CLIENT_NAME"
          prop="client.clientName"
          sortable="custom"
          align="left"
        >
          <template slot-scope="scope">
            {{ scope.row.client.clientName }}
            <fks-button
              type="primary"
              size="mini"
              v-if="scope.row.client.clientId == 'fawkes'"
            >
              {{ LANG.TENANT_CONSOLE }}
            </fks-button>
          </template>
        </fks-table-column> -->
        <fks-table-column
          :label="LANG.REMARK"
          prop="client.remark"
          align="left"
        >
          <template slot-scope="scope">
            <fks-tooltip
              v-if="
                scope.row.client.remark && scope.row.client.remark.length > 50
              "
              :content="scope.row.client.remark"
              placement="top"
            >
              <p class="remark-style">{{ scope.row.client.remark }}</p>
            </fks-tooltip>
            <p v-else>{{ scope.row.client.remark }}</p>
          </template>
        </fks-table-column>

        <fks-table-column
          :label="LANG.REDIRECT_URL"
          prop="client.webServerRedirectUri"
          align="left"
        />
        <!-- <fks-table-column
          :label="LANG.CLIENT_ID"
          prop="client.clientId"
          align="left"
        />
        <fks-table-column
          :label="LANG.CLIENT_SECRET"
          prop="client.clientSecret"
          align="left"
        /> -->
        <!-- <fks-table-column prop="tenantId" label="租户管理员账号" align="left" /> -->
        <fks-table-column :label="LANG.OPERATION" align="center" width="220px">
          <template slot-scope="scope">
            <fks-button text @click="adminHandle(scope.row)">
              {{ LANG.ADMIN }}
            </fks-button>
            <fks-button text @click="viewHandle(scope.row)">
              {{ LANG.CLIENT_DETAIL }}
            </fks-button>

            <fks-button
              v-permission="['tenant:edit']"
              text
              @click="editHandle(scope.row)"
            >
              {{ LANG.EDIT }}
            </fks-button>
            <fks-button
              v-permission="['tenant:delete']"
              danger-text
              @click="deleteHandle(scope.row)"
            >
              {{ LANG.DELETE }}
            </fks-button>
          </template>
        </fks-table-column>
      </template>
    </fks-query-page>
    <tenant-init :visible.sync="drawerVisible" @onSave="onSave"></tenant-init>
    <tenant-admin
      :visible.sync="adminVisible"
      :tenant-config="tenantInEdit"
    ></tenant-admin>
    <tenant-edit
      :type="dialogType"
      :visible.sync="editorVisible"
      @onSave="onSave"
      :tenantIdInDataBase="tenantIdInDataBase"
      :clientIdInDataBase="clientIdInDataBase"
    ></tenant-edit>
    <default-client
      :visible.sync="clientVisible"
      @onSave="onSave"
      :clientIdInDataBase="clientIdInDataBase"
    ></default-client>
  </div>
</template>
<script>
import TenantInit from '../components/TenantInit'
import TenantAdmin from '../components/TenantAdmin'
import TenantEdit from '../components/TenantEdit'
import DefaultClient from '../components/DefaultClient'
import * as Tenant from '../api'
import { DATA_MODE_TYPE, MASTER_DATA_TYPE } from '@/config/enums'
import deepmerge from 'deepmerge'
import { matchTimestampToFormat } from '@/utils/timezone'

export default {
  name: 'Tenant',
  components: { TenantEdit, TenantAdmin, TenantInit, DefaultClient },
  data() {
    return {
      currentPage: 1,
      pageSize: 20,
      total: 0,
      sort: '',
      sortColumn: '',

      tableData: [],
      loading: false,

      drawerVisible: false,
      adminVisible: false,
      editorVisible: false,
      clientVisible: false,

      dialogType: 'edit',

      tenantInEdit: {},
      tenantIdInDataBase: '',
      clientIdInDataBase: '',

      Form: {
        tenantName: '',
        orgNo: '',
        orgName: '',
        initTenantData: false
      }
    }
  },
  computed: {
    tableDataForShow() {
      let obj = { client: {} }
      return this.tableData.map((item) => {
        return deepmerge(obj, item)
      })
    },
    MasterDataMap() {
      let obj = {}
      obj[MASTER_DATA_TYPE.USER] = this.LANG.USER_DATA
      obj[MASTER_DATA_TYPE.ORG] = this.LANG.ORG_DATA
      obj[MASTER_DATA_TYPE.DIC] = this.LANG.DIC_DATA

      return obj
    }
  },
  watch: {},
  created() {
    this.getData()
  },
  methods: {
    getMasterData(row) {
      let data = row.client
      if (!data.hasOwnProperty('additionalInformation')) {
        return
      }
      if (!data.additionalInformation) {
        return
      }
      let additionalInformation = JSON.parse(
        matchTimestampToFormat(data.additionalInformation)
      )
      let dataMode = additionalInformation?.dataMode || {}
      let arr = []
      for (let [key, value] of Object.entries(dataMode)) {
        if (value !== DATA_MODE_TYPE.MASTER) {
          continue
        }
        arr.push(this.MasterDataMap[key])
      }
      return arr
    },
    /**
     * @description: 根据所选列表字段排序
     */
    tenantSortHandler(data) {
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName =
          data.prop == 'tenantName' ? 'tenant_name' : 'client_name'
      }
      this.getData()
    },
    /**
     * @description: 主动清空排序条件
     */
    clearSort() {
      this.$refs['tenantTable'].clearSort()
      this.sort = ''
      this.columnName = ''
    },
    /**
     * @description: 获取租户分页
     */
    getData() {
      let params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getTenantList(params)
    },
    getTenantList(data) {
      this.loading = true
      Tenant.getTenantInSaas(data)
        .then((res) => {
          if (res.status && res.data) {
            this.size = res.data.size
            this.total = res.data.total
            this.tableData = res.data.list
          }
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    adminHandle(row) {
      let { clientId, tenantId } = row.client
      this.tenantInEdit = { clientId, tenantId }
      this.adminVisible = true
    },

    viewHandle(row) {
      this.clientIdInDataBase = row.client.id
      this.clientVisible = true
    },

    editHandle(row) {
      this.openEditorVisible(row)
    },

    openEditorVisible(row, dialogType = 'edit') {
      this.dialogType = dialogType
      this.tenantIdInDataBase = row.id
      this.clientIdInDataBase = row.client.id
      this.editorVisible = true
    },

    /**
     * @description: 根据id删除租户，需要弹窗确认
     */
    deleteHandle(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          Tenant.deleteTenant(row.id)
            .then((res) => {
              if (res.status) {
                this.$message.success(this.LANG.DELETE_SUCCESS)
                if (this.tableData.length <= 1 && this.currentPage > 1) {
                  this.currentPage--
                }
                this.getData()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    /**
     * @description: 新增租户抽屉
     */
    addHandle() {
      this.drawerVisible = true
    },
    /**
     * @description: 租户信息修改/新增成功后的回调
     *               关闭弹窗
     *               如果是新增，去除排序条件并回到第一页，保证能看到新增的数据。否则维持当前搜索条件
     */
    onSave(type = 'edit') {
      this.drawerVisible = false
      this.adminVisible = false
      this.editorVisible = false
      this.clientVisible = false

      if (type == 'add') {
        this.currentPage == 1
        this.clearSort()
      }
      this.getData()
    }
  }
}
</script>
<style lang="scss" scoped>
.tenant-container {
  min-width: 632px;
}

::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
.remark-style {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3; //行数
  -webkit-box-orient: vertical;
}
</style>